package com.ldc.commonlibs.http

import com.ldc.commonlibs.http.conf.ApiConf
import com.ldc.commonlibs.http.conf.LogConf
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitClientBase {
    private val okHttpClient: OkHttpClient by lazy { getClient() }

    companion object {
        fun getInstance(): RetrofitClientBase = Singleton.instance
    }

    private object Singleton {
        val instance = RetrofitClientBase()
    }

    private fun getClient(): OkHttpClient =
        OkHttpClient.Builder()
            .readTimeout(120, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(2, TimeUnit.SECONDS)
            .addNetworkInterceptor(LogConf.getLoggger(HttpLoggingInterceptor.Level.HEADERS))
            .addInterceptor(WanAndroidCookieJar())
            .addInterceptor(LoinInterceptor())
            .build()


    private fun getRetrofit(url: String): Retrofit {
        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }


    fun <T> createServer(base_url: String, clazz: Class<T>): T =
        getRetrofit(base_url).create(clazz)

    fun <T> createServer(clazz: Class<T>): T =
        getRetrofit(ApiConf.BASE_URL).create(clazz)


}